package app

import (
	"bufio"
	"fmt"
	"golang.org/x/crypto/ssh"
	exec "golang.org/x/sys/execabs"
	"strconv"
)

type SShClient struct {
	Host     string
	Port     int
	User     string
	Password string
}

func (node *SShClient) client() *ssh.ClientConfig {
	if node.Port == 0 {
		node.Port = 22
	}
	return &ssh.ClientConfig{
		User: node.User,
		Auth: []ssh.AuthMethod{
			ssh.Password(node.Password),
		},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}
}

func (node *SShClient) Run(cmd string) string {
	host := node.Host + ":" + strconv.Itoa(node.Port)
	client, err := ssh.Dial("tcp", host, node.client())
	if err != nil {
		panic(err)
	}
	defer client.Close()

	session, err := client.NewSession()
	if err != nil {
		panic(err)
	}
	defer session.Close()

	output, err := session.Output(cmd)
	if err != nil {
		panic(err)
	}
	return string(output)
}

func ExecCommand(cmdstr string, response chan string) {
	cmd := exec.Command("/bin/bash", "-c", cmdstr)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Println(err)
		return
	}

	if err = cmd.Start(); err != nil {
		fmt.Println(err)
		return
	}

	scanner := bufio.NewScanner(stdout)
	defer close(response)
	for scanner.Scan() {
		txt := scanner.Text()
		fmt.Println(txt)
		response <- txt
	}
	if err = scanner.Err(); err != nil {
		fmt.Println(err)
		return
	}
	if err = cmd.Wait(); err != nil {
		fmt.Println(err)
		return
	}
}
